/**
 * 20080205 1050: Eric Kao, use E885Logger to get Logger<br>
 * 20080102 1500: Eric Kao was created.
 */

package com.e885.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import com.e885.exception.E885DBException;
import com.e885.log.E885Logger;

/**
 * 這是一個 JDBC Util, 我們要使用的資料庫有太多種, 所以都要繼承這個 class.<br>
 * <br>
 * Copyright: Copyright (c) 2001-2008<br>
 * Company: E885 Group
 * 
 * @author Eric.Kao(gau168.gau@msa.hinet.net)
 * @version 1.0
 */
public abstract class JDBCUtil
{
	/**
	 * valid driver
	 * 
	 * @throws E885DBException
	 */
	public void validDriver()
		throws E885DBException
	{
		try
		{
			E885Logger.jdbcLog.debug( "driver name:" + getDriverName() );

			Class.forName( getDriverName() );
		}
		catch( ClassNotFoundException ex )
		{
			String temp = "Can not load driver.";

			E885Logger.jdbcLog.error( temp, ex );

			throw new E885DBException( temp );
		}
	}

	/**
	 * get a jdbc connection
	 * 
	 * @return a jdbc connection
	 * @throws E885DBException
	 */
	public Connection getConnection()
		throws E885DBException
	{
		validDriver();

		E885Logger.jdbcLog.debug( "url:" + getUrl() );
		E885Logger.jdbcLog.debug( "user name:" + getUserName() );
		E885Logger.jdbcLog.debug( "password:" + getPassword() );

		Connection connection;

		try
		{
			connection = DriverManager.getConnection( getUrl(), getUserName(), getPassword() );

			if( connection == null )
			{
				String temp = "Can not get the connection.";

				E885Logger.jdbcLog.error( temp );

				throw new E885DBException( temp );
			}
			else
			{
				if( connection.isClosed() )
				{
					String temp = "Open database is failed.";

					E885Logger.jdbcLog.error( temp );

					throw new E885DBException( temp );
				}
				else
				{
					return connection;
				}
			}
		}
		catch( SQLException ex )
		{
			String temp = "Open database is error";

			E885Logger.jdbcLog.error( temp, ex );

			throw new E885DBException( temp );
		}
	}

	/**
	 * the driver name of the database
	 * 
	 * @return a driver name
	 */
	protected abstract String getDriverName();

	/**
	 * the url to connect the database
	 * 
	 * @return a url
	 */
	protected abstract String getUrl();

	/**
	 * the user name to connect the database
	 * 
	 * @return a user name
	 */
	protected abstract String getUserName();

	/**
	 * the password to connection the database
	 * 
	 * @return a password
	 */
	protected abstract String getPassword();
}
